//
//  LLBBaseViewController.swift
//  LLBBaseVC
//
//  Created by Yun on 2018/11/1.
//

import UIKit
import LLBUtil
import Toast_Swift

public struct ImagesHelper {
    private static var podsBundle: Bundle {
        let frameworkBundle = Bundle(for: LLBBaseViewController.self)
        let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("LLBBaseVC.bundle")
        let resourceBundle = Bundle(url: bundleURL!)
        return resourceBundle!
    }
    
    private static func imageFor(name imageName: String) -> UIImage? {
        return UIImage.init(named: imageName, in: podsBundle, compatibleWith: nil)
    }
    
    public static var default_back_image: UIImage? {return imageFor(name: "llb_base_back")}//默认返回按钮
    public static var default_empty_image: UIImage? {return imageFor(name: "llb_base_empty")}//默认empty空
}

open class AKNavigationItem {
    var title: String = ""
    var image: UIImage?
    var action: (()->Void)?
    
    public init(_ title: String, action:@escaping ()->Void) {
        self.title = title
        self.action = action
    }
    
    public init(_ image: UIImage?, action:@escaping ()->Void) {
        self.image = image
        self.action = action
    }
    
    @objc func itemAction() {
        if let _ = action {
            action!()
        }
    }
}

open class LLBBaseViewController: UIViewController {

    public var defaultLeftImage:UIImage?//可以修改默认返回按钮图片
    public var navigationBackGroundColor: UIColor?{//navigationbar颜色
        didSet{
            if let c = navigationBackGroundColor{
                self.navigationController?.navigationBar.LLB_setBackgroundColor(backgroundColor: c)
            }
        }
    }
    public var navigationTitleColor: UIColor?{//navigationbar标题颜色
        didSet{
            if let c = navigationTitleColor{
                self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:c]
            }
        }
    }
    public var popGestureRecognizerDissable:Bool?//是否禁止滑动返回手势
    
    // MARK: left bar button item
    public var leftTitle: String? {
        didSet {
            if leftTitle != nil && !leftTitle!.isEmpty {
                navigationItem.leftBarButtonItem = UIBarButtonItem(title: leftTitle, style: .plain, target: self, action: #selector(navLeft))
                navigationItem.leftBarButtonItem?.tintColor = leftButtonColor
                navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:leftButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.normal)
                navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:leftButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.selected)
                navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:leftButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.disabled)
                
            } else {
                navigationItem.leftBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var leftImage: UIImage? {
        didSet {
            if let _ = leftImage {
                navigationItem.leftBarButtonItem = UIBarButtonItem(image: leftImage!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(navLeft))
                navigationItem.leftBarButtonItem?.tintColor = leftButtonColor
            } else {
                navigationItem.leftBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var leftItems: [AKNavigationItem]? {
        didSet {
            if leftItems != nil && !leftItems!.isEmpty {
                var barButtonItems = [UIBarButtonItem]()
                for item in leftItems! {
                    if let _ = item.image {
                        let barButtonItem = UIBarButtonItem(image: item.image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), style: .plain, target: item, action: #selector(item.itemAction))
                        barButtonItem.tintColor = leftButtonColor
                        barButtonItems.append(barButtonItem)
                    } else {
                        let barButtonItem = UIBarButtonItem(title: item.title, style: .plain, target: item, action: #selector(item.itemAction))
                        barButtonItem.tintColor = leftButtonColor
                        barButtonItems.append(barButtonItem)
                    }
                }
                navigationItem.leftBarButtonItems = barButtonItems
            } else {
                navigationItem.leftBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var leftButtonColor: UIColor = UIColor.white { // MARK:here to change default left bar color
        didSet {
            if let _ = navigationItem.leftBarButtonItems {
                for item in navigationItem.leftBarButtonItems! {
                    item.tintColor = leftButtonColor
                }
            }
        }
    }
    
    // MARK: right bar button item
    public var rightTitle: String? {
        didSet {
            if rightTitle != nil && !rightTitle!.isEmpty {
                navigationItem.rightBarButtonItem = UIBarButtonItem(title: rightTitle, style: .plain, target: self, action: #selector(navRight))
                navigationItem.rightBarButtonItem?.tintColor = rightButtonColor
                navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:rightButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.normal)
                navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:leftButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.selected)
                navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:leftButtonColor,NSAttributedString.Key.font:llbFont(size: 15)], for: UIControl.State.disabled)
                
            } else {
                navigationItem.rightBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var rightImage: UIImage? {
        didSet {
            if let _ = rightImage {
                navigationItem.rightBarButtonItem = UIBarButtonItem(image: rightImage!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(navRight))
                navigationItem.rightBarButtonItem?.tintColor = rightButtonColor
            } else {
                navigationItem.rightBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var rightItems: [AKNavigationItem]? {
        didSet {
            if rightItems != nil && !rightItems!.isEmpty {
                var barButtonItems = [UIBarButtonItem]()
                for item in rightItems! {
                    if let _ = item.image {
                        let barButtonItem = UIBarButtonItem(image: item.image!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), style: .plain, target: item, action: #selector(item.itemAction))
                        barButtonItem.tintColor = rightButtonColor
                        barButtonItems.append(barButtonItem)
                    } else {
                        let barButtonItem = UIBarButtonItem(title: item.title, style: .plain, target: item, action: #selector(item.itemAction))
                        barButtonItem.tintColor = rightButtonColor
                        barButtonItems.append(barButtonItem)
                    }
                }
                navigationItem.rightBarButtonItems = barButtonItems
            } else {
                navigationItem.rightBarButtonItem = UIBarButtonItem(title: "  ", style: .plain, target: nil, action: nil)
            }
        }
    }
    
    public var rightButtonColor: UIColor = UIColor.white { // MARK:here to change default right bar color
        didSet {
            if let _ = navigationItem.rightBarButtonItems {
                for item in navigationItem.rightBarButtonItems! {
                    item.tintColor = rightButtonColor
                }
            }
        }
    }
    
    // MARK: - 方法开始
    override open func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        if(self.navigationController != nil && (self.navigationController?.viewControllers.count)!>1){
            self.setDefaultLeftButton()
        }
    }
    
    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if((self.navigationController != nil && (self.navigationController?.viewControllers.count) == 1) || popGestureRecognizerDissable ?? false){
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        }
    }
    
    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let p = popGestureRecognizerDissable, p == true{
            return
        }
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    

    @objc open func navLeft() {
        if navigationController != nil &&
            navigationController!.viewControllers.count > 1 &&
            navigationController!.viewControllers.last == self {
            let _ = navigationController?.popViewController(animated: true)
        }
    }
    
    @objc open func navRight() {}
    
    deinit {
        DBLog("\(NSStringFromClass(type(of: self)) as String) deinit")
    }
    
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    open func pushAnimator() -> UIViewControllerAnimatedTransitioning? { return nil }
    open func popAnimator() -> UIViewControllerAnimatedTransitioning? { return nil }
    
    func setDefaultLeftButton() {
        if let img = defaultLeftImage {
            leftImage = img.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        }else{
            leftImage = ImagesHelper.default_back_image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        }
    }
    
    /// 显示加载菊花
    public func showHud(){
        DispatchQueue.main.safeAsync {
            ToastManager.shared.style.activityBackgroundColor = UIColor.hex(from: 0xFF999999)
            UIApplication.shared.keyWindow?.isUserInteractionEnabled = false
            UIApplication.shared.keyWindow?.makeToastActivity(.center)
        }
    }
    
    /// 隐藏菊花
    public func hideHud(){
        DispatchQueue.main.safeAsync {
            UIApplication.shared.keyWindow?.isUserInteractionEnabled = true
            UIApplication.shared.keyWindow?.hideToastActivity()
        }
    }
}
